package com.cctc.rds.nrpc.core.protocol.codec;

import com.cctc.rds.nrpc.core.protocol.message.MessageVersion;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class MessageUnpacket extends LengthFieldBasedFrameDecoder {
    public static final int LENGTH_FIELD_OFFSET = MessageVersion.MAGIC.length + 3;
    public static final int LENGTH_FIELD_LENGTH = 4;

    public MessageUnpacket() {
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame != null) {
            byte[] magic = new byte[MessageVersion.MAGIC.length];
            frame.readBytes(magic);
            frame.resetReaderIndex();
            for (int i = 0; i < magic.length; i++) {
                if (magic[i] != MessageVersion.MAGIC[i]) {
                    return null;
                }
            }
        }
        return frame;
    }
}
